package cn.wolfcode.crm.serivce.impl;

import cn.wolfcode.crm.domain.Gift;
import cn.wolfcode.crm.domain.Member;
import cn.wolfcode.crm.mapper.GiftMapper;
import cn.wolfcode.crm.mapper.MemberMapper;
import cn.wolfcode.crm.query.GiftQueryObject;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.serivce.IGiftService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;


@Service
public class GiftServiceImpl implements IGiftService {
    @Autowired
    private GiftMapper mapper;
    @Autowired
    private MemberMapper memberMapper;
    @Override
    public void deleteByPrimaryKey(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(Gift record) {
        if (record.getId() == null) {
            //保存操作
            mapper.insert(record);
        }else {
            mapper.updateByPrimaryKey(record);
        }
    }

    @Override
    public Gift selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public PageResult query(GiftQueryObject qo) {

        Integer total = mapper.count(qo);
        if (total > 0) {
            List<Gift> rows = mapper.query(qo);

            return new PageResult(total,rows);
        }
        return new PageResult(0, Collections.EMPTY_LIST);
    }

    @Override
    public List<Gift> selectAll() {
        return mapper.selectAll();
    }
    @Override
    public void updatePoint(Gift gift) {
        Member member = new Member();
        Gift old = mapper.selectByPrimaryKey(gift.getId());
        Integer points = old.getInte();
        Integer number = gift.getNumber();
        int i = points*number;
        Long d = gift.getId();
        member.setId(d);
        Member memberId = memberMapper.selectByPGiftKey(d);
        int newPoint=memberId.getPoints()-i;
        member.setPoints(newPoint);
        Integer endNumber = old.getEndNumber();
        int newEndNumber = endNumber-number;
        Date date = new Date();
        gift.setRecordTime(date);
        gift.setTotalPoint(i);
        gift.setEndNumber(newEndNumber);
        gift.setNumber(number);
        mapper.updateNumber(gift);
        memberMapper.updateNewPoint(member);
    }

    @Override
    public List<Gift> recordGift() {
        return mapper.recordGift();
    }

}
